package com.mzy.linear_struct.ks;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: mizy3
 * @Date: 2024/08/25/下午5:12
 * @Description:
 */
public class 三数之和 {
/*    public List<List<Integer>> threeSum(int[] nums) {
        if (nums.length < 2) return null;
        Arrays.sort(nums);
        //              r
        // -4 -1 -1 0 1 2
        //     i
        //          l
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;
            if(i > 0 && nums[i] == nums[i - 1]){
                continue;
            }
            while (l < r) {
                int sum = nums[l] + nums[i] + nums[r];
                if(sum == 0){
                    ans.add(Arrays.asList(nums[l], nums[i], nums[r]));

                    while (l < r && nums[l] == nums[l + 1]){
                        l++;
                    }
                    while (l < r && nums[r] == nums[r - 1]){
                        r--;
                    }
                    l++;
                    r--;
                }else if(sum > 0){
                    r--;
                }else if(sum < 0){
                    l++;
                }
            }
        }
        return ans;
    }*/


    public static void main(String[] args) {
        System.out.println(new 三数之和().threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
    }

    private List<List<Integer>> threeSum(int[] nums) {

        Arrays.sort(nums);
        List<List<Integer>> ans = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {

            int l = i + 1;
            int r = nums.length - 1;
            //              r
            // -4 -1 -1 0 1 2
            //  i
            //     l
            if (i >= 1 && nums[i] == nums[i - 1]) {
                continue;
            }

            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == 0) {
                    ans.add(Arrays.asList(nums[i], nums[l], nums[r]));
                    while (l < r && nums[l] == nums[l + 1]) {
                        l++;
                    }
                    while (l < r && nums[r] == nums[r - 1]) {
                        r--;
                    }
                    l++;
                    r--;
                } else if (sum < 0) {
                    l++;
                } else if (sum > 0) {
                    r--;
                }
            }
        }

        return ans;
    }
}















